package com.abigdreamer.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Random;

public class FileUtil
{
  public static String getRandomEndsWithFileName(String dir,final String endsWith)
  {
    String[] fileNames = new File(dir).list(new FilenameFilter()
    {
      public boolean accept(File dir, String name)
      {
        return name.toLowerCase().endsWith(endsWith);
      }
    });
    int count = fileNames.length;
    if (count > 0)
    {
      int index = new Random().nextInt(count);
      return fileNames[index];
    }
    return "";
  }
  
  public static boolean checkFileIsLock(String file)
    throws IOException
  {
    RandomAccessFile raf = null;
    try
    {
      raf = new RandomAccessFile(file, "rwd");
      FileChannel channel = raf.getChannel();
      FileLock lock = channel.tryLock();
      if (lock == null) {
        return true;
      }
      lock.release();
      return false;
    }
    catch (FileNotFoundException e)
    {
      e.printStackTrace();
      return false;
    }
    finally
    {
      try
      {
        if (raf != null) {
          raf.close();
        }
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
    }
  }
}
